<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.goods_stock_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出入库时间">
        <el-date-picker
          v-model="daterangeBusiDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.goods_stock_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="storeId">
        <el-select
          v-model="queryParams.storeId"
          placeholder="请选择仓库"
          clearable
        >
          <el-option
            v-for="store in storeListData"
            :key="store.id"
            :label="store.storeName"
            :value="store.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(0)"
          v-hasPermi="['team:stockBill:add']"
          >入库</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(1)"
          v-hasPermi="['team:stockBill:add']"
          >出库</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="stockBillList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.goods_stock_type"
            :value="scope.row.type"
          />
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="storeName" />
      <el-table-column label="总数量" align="center" prop="totalNum" />
      <el-table-column label="总金额" align="center" prop="totalMoney" />
      <el-table-column label="录入人" align="center" prop="operatorName" />
      <el-table-column
        label="出入库时间"
        align="center"
        prop="busiDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.busiDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="录入时间"
        align="center"
        prop="operateDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operateDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.goods_stock_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.status != -1"
            @click="handleDelete(scope.row)"
            v-hasPermi="['team:stockBill:remove']"
            >作废</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['team:stockBill:edit']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出入库单据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body @closed="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库" prop="storeId">
              <el-select v-if="showInfo"
                v-model="form.storeId"
                placeholder="请选择仓库"
                clearable
              >
                <el-option
                  v-for="store in storeListData"
                  :key="store.id"
                  :label="store.storeName"
                  :value="store.id"
                />
              </el-select>
              <el-select v-if="!showInfo" disabled
                         v-model="form.storeId"
                         placeholder="请选择仓库"
                         clearable
              >
                <el-option
                  v-for="store in storeListData"
                  :key="store.id"
                  :label="store.storeName"
                  :value="store.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">&nbsp;</el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出入库时间" prop="busiDate">
              <el-date-picker
                clearable
                v-model="form.busiDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择出入库时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">&nbsp;</el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">&nbsp;</el-col>
        </el-row>
      </el-form>
      <!-- 添加明细 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5" v-if="showInfo">
          <el-button
            v-show="isInput"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddStockItem(0)"
            v-hasPermi="['team:stockBill:add']"
          >添加明细</el-button>
          <el-button
            v-show="!isInput"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddStockItem(1)"
            v-hasPermi="['team:stockBill:add']"
          >添加明细</el-button>
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <!-- 表格部分 -->
      <el-table :data="form.list" border>
        <el-table-column label="序号" align="center" prop="id" />
        <el-table-column label="物品" align="center" prop="goodName" />
        <el-table-column label="价格" align="center" prop="price">
          <template v-slot="scope">
            <el-input v-model="scope.row.price" />
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="amounts">
          <template v-slot="scope">
            <el-input v-model="scope.row.amounts" />
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center">
          <template v-slot="scope">
            {{scope.row.price * scope.row.amounts | computedFilter}}
          </template>
        </el-table-column>
        <el-table-column v-if="showInfo"
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleStockItemDelete(scope.row)"
              v-hasPermi="['team:stockBill:remove']"
            >删除</el-button
            ></template></el-table-column>
      </el-table >

      <div slot="footer" class="dialog-footer" >
        <el-button v-if="showInfo" type="primary" @click="submitForm">确 定</el-button>
        <el-button v-if="showInfo" @click="cancel">取 消</el-button>
        <el-button v-if="!showInfo" @click="handleClose">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 出库表 -->
    <el-dialog :title="title" :visible.sync="outForm" width="70%" append-to-body>
      <!-- 表格部分 -->
      <el-table :data="goodsList" border>
        <el-table-column label="序号" align="center" prop="id" />
        <el-table-column label="物品" align="center" prop="goodsCover" />
        <el-table-column label="名称" align="center" prop="goodsName" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="分类" align="center" prop="categoryId" />
        <el-table-column label="数量" align="center" prop="" />
        <el-table-column v-if="showInfo"
                         label="操作"
                         align="center"
                         class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleChoose(scope.row)"
              v-hasPermi="['team:stockBill:remove']"
            >选择此物品</el-button
            ></template></el-table-column>
      </el-table >

    </el-dialog>
    </div>
</template>

<script>
import {
  listStockBill,
  getStockBill,
  delStockBill,
  addStockBill,
  updateStockBill,
  getGoodListByStoreId,
  deleteStockBill
} from "@/api/team/stockBill";

import {
  listGoods,
  getGoods,
  addGoods,
  updateGoods,
} from "@/api/team/goods";

import { listStockItem, delStockItem, addStockItem } from "@/api/team/stockItem";
import { listStore } from "@/api/team/store";

export default {
  name: "StockBill",
  dicts: ["goods_stock_type", "goods_stock_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出入库单据表格数据
      stockBillList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isInput: true,
      outForm: false,
      // 备注时间范围
      daterangeBusiDate: [],
      emTableData: [],
      stockItemTableData: [],
      cacheStockItemTableData: [],
      goodsList: [],
      // 模拟 id
      cacheId: 1,
      // 仓库数据
      storeListData: [],
      showInfo: true,
      // 商品 id
      goodId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        storeId: null,
        busiDate: null,
        status: null,
      },
      // 表单参数
      form: {
        type: null,
        status: -1,
        storeId: null,
        list: []
      },
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: "仓库不能为空", trigger: "change" },
        ],
        busiDate: [
          { required: true, message: "出入库时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    $route: {
      deep: true,
      handler(to, from) {
        if (from.name === 'Goods') {
          // this.goodId = to.query.goodId;
          let newCacheList = this.cacheStockItemTableData.filter(item => {
            return item.goodsId == to.query.good.id;
          })

          let stockItem = {
            id : this.cacheId,
            goodsId: to.query.good.id,
            goodName: to.query.good.goodsName,
            price: 0,
            amounts: 1,
          }
          let forData = this.cacheStockItemTableData;
          if (newCacheList.length > 0) {
            for (let i = 0; i < forData.length; i++) {
              if (forData[i].goodsId == newCacheList[0].goodsId) {
                forData[i].amounts += 1;
              }
            }
          } else {
            this.cacheStockItemTableData.push(stockItem);
          }
        }
      }
    },
    cacheStockItemTableData: {
      deep: true,
      immediate: false,
      handler(newVal, oldVal) {
        this.cacheId += 1;
        this.form.list = newVal;
        this.open = true;
        if (newVal) {
          let paramsForm = {
            amounts: 0,
            price: 0,
            goodsId: this.goodId,
          }

          // let temp = this.form.list;
          // let newList = temp.filter(item => {
          //   return item.goodsId == this.goodId;
          // });
          //
          // if (newList.length > 1) {
          //   this.$message.error("不能重复添加商品");
          // } else {
          //   addStockItem(paramsForm).then(res => {
          //     this.open = true;
          //     this.getStockItemList();
          //     this.$message.success("添加成功!");
          //   })
          // }
        }
      }
    },
    // 监听价格和数量的改变,自动计算总价格,并持久保存到数据库
    stockItemTableData: {
      deep: true,
      handler(newVal, oldVal) {

      }
    }
  },
  filters: {
    computedFilter(total) {
      return !isNaN(total) ? total : 0
    }
  },
  created() {
    this.getList();
    this.getStoreList();
    // this.getGoodListByStoreData();
  },
  methods: {
    handleClose() {
      this.showInfo = true;
      this.open = false;
    },
    getGoodListByStoreData() {
      getGoodListByStoreId(this.form.storeId).then(res => {
        console.log(res.rows);
      })
    },
    getGoodList() {
      this.loading = true;
      listGoods(this.form.storeId).then((response) => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询出入库单据列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeBusiDate && "" != this.daterangeBusiDate) {
        this.queryParams.params["beginBusiDate"] = this.daterangeBusiDate[0];
        this.queryParams.params["endBusiDate"] = this.daterangeBusiDate[1];
      }
      listStockBill(this.queryParams).then((response) => {
        this.stockBillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取出入单明细请求接口
    // 注意初始化数据为空,清空之前的查询数据
    getStockItemList() {
      listStockItem().then((res) => {
        this.form.list = null;
      });
    },
    getStoreList() {
      listStore().then(res => {
        this.storeListData = res.rows;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        storeId: null,
        busiDate: null,
        status: null,
        operateDate: null,
        operatorId: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮录入 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮录入 */
    resetQuery() {
      this.daterangeBusiDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 选择要出库的商品 */
    handleChoose(row) {

    },
    /** 新增按钮操作 */
    handleAdd(type) {
      this.reset();
      this.open = true;
      this.form.type = type;
      if(type === 0) {
        // 点击入库获取仓库信息
        this.getStockItemList();
        this.title = "添加入库单据";
      }
      if (type === 1) {
        this.isInput = false;
        this.getGoodList();
        this.title = "添加出库单据";
      }
    },
    // 添加明细
    handleAddStockItem(type) {
      // if (type === 0) {
        this.open = false;
        this.$router.push("/goods/goods");
      // }
      // if (type === 1) {
      //   this.outForm = true;
      // }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getStockBill(id).then((response) => {
        this.form = response.data;
        this.showInfo = false;
        this.open = true;
        this.title = "查看出入库单据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateStockBill(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.isInput) {
              addStockBill(this.form).then(response => {
                this.$modal.msgSuccess("入库成功");
                this.open = false;
                this.getList();
              });
            } else {
              deleteStockBill(this.form).then(response => {
                this.$modal.msgSuccess("出库成功");
                this.open = false;
                this.getList();
              }).catch(res=> {
                console.log(res)});
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认作废出入库单据编号为"' + ids + '"的数据项？')
        .then(function () {
          return delStockBill(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("作废成功");
        })
        .catch(() => {});
    },
    // 根据 id 删除明细
    handleStockItemDelete(row) {
      let id = row.id;
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delStockItem(id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getStockItemList();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "team/stockBill/export",
        {
          ...this.queryParams,
        },
        `stockBill_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
